package com.example.blood_sugar.fragments;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.blood_sugar.R;
import com.example.blood_sugar.bean.BSRecord;
import com.example.blood_sugar.db.BSRecordHolder;
import com.example.blood_sugar.utils.DateUtil;
import com.example.blood_sugar.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 添加血压记录的fragment
 */
public class AddBloodPressureRecordFragment extends BaseFragment {

    private BSRecord mBSRecord;

    private EditText mEditText;
    private TextView mTextView1; // 收缩压的TextView
    private TextView mTextView2; // 舒张压的Text'veiw

    private List<TextView> mTextViews; // 上面两个的list

    private ImageView left; // 顶部菜单 返回ImageView
    private TextView middleTV; // 中间的TextVeiw
    private ImageView middle; //中间的ImageView
    private TextView right; // 右边的保存TextView

    private Button reset; // 重置按钮

    private String text; // 输入的信息

    long value; // 创建本fragment时闯入的值

    int sign; // 标记，详见BSRecord类

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        value = getArguments().getLong("value");
    }

    /**
     * 获得本类实例
     * @param value
     * @return
     */
    public static AddBloodPressureRecordFragment newInstance(long value){
        Bundle bundle = new Bundle();
        bundle.putLong("value",value);
        AddBloodPressureRecordFragment addBloodSugarRecordFragment = new AddBloodPressureRecordFragment();
        addBloodSugarRecordFragment.setArguments(bundle);
        return addBloodSugarRecordFragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_blood_pressure_record, container, false);
        BSRecord bsRecord = BSRecordHolder.get(getContext()).getRSRecordByTime(value / 10);
        if (bsRecord == null) throw new RuntimeException("没找到记录：" + new Date(value / 10));
        sign = 10 + (int) (value % 10);
        mBSRecord = bsRecord;
        text = "" + mBSRecord.getDataBySign(sign);

        left = view.findViewById(R.id.btn_top_left);
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
        middleTV = view.findViewById(R.id.tv_center);
        middleTV.setText(DateUtil.date2Str(mBSRecord.getDate(), "MM月dd日"));
        middle = view.findViewById(R.id.down);
        middle.setVisibility(View.GONE);
        right = view.findViewById(R.id.btn_top_right);
        right.setText("保存");
        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });

        mEditText = view.findViewById(R.id.BloodSugarEditText);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // This space intentionally left blank
            }

            @SuppressLint("ResourceAsColor")
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    text = "" + mBSRecord.getDataBySign(sign);
                } else {
//                mBSRecord.setDataBySign(sign, Double.parseDouble(s.toString()));
                    text = s.toString();

                    // 点击消失的动画（如果系统支持 api>=21）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        int cx = reset.getWidth() / 2;
                        int cy = reset.getHeight() / 2;
                        float radius = reset.getWidth();
                        Animator anim = ViewAnimationUtils.createCircularReveal(reset, cx, cy, 0, radius);
                        anim.addListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                super.onAnimationEnd(animation);
                                reset.setVisibility(View.VISIBLE);
                            }
                        });
                        anim.start();
                    } else { // 不支持动画，则直接设置不可见
                        reset.setVisibility(View.VISIBLE);
                        reset.setBackgroundColor(R.color.bgColor);
                        reset.setTextColor(Color.GRAY);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                // this one too
            }
        });
        mTextView1 = view.findViewById(R.id.textView1);
        mTextView2 = view.findViewById(R.id.textView2);
        mTextViews = new ArrayList<>();
        mTextViews.add(mTextView1);
        mTextViews.add(mTextView2);
        for (int i = 0; i < mTextViews.size(); i ++) {
            mTextViews.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int j = 0; j < mTextViews.size(); j ++) {
                        mTextViews.get(j).setBackgroundResource(R.color.arc_inteval);
                    }
                    v.setBackgroundColor(getResources().getColor(R.color.fill));
                    updateSign();
                }
            });
            if (i == sign%10 - 1) {
                mTextViews.get(i).setBackgroundColor(getResources().getColor(R.color.fill));
            }
        }

        mEditText.setHint("" + mBSRecord.getDataBySign(sign));

        reset = view.findViewById(R.id.reset_btn);
        reset.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceAsColor")
            @Override
            public void onClick(View v) {
                // 点击消失的动画（如果系统支持 api>=21）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    int cx = reset.getWidth() / 2;
                    int cy = reset.getHeight() / 2;
                    float radius = reset.getWidth();
                    Animator anim = ViewAnimationUtils.createCircularReveal(reset, cx, cy, radius, 0);
                    anim.addListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            super.onAnimationEnd(animation);
                            reset.setVisibility(View.INVISIBLE);
                        }
                    });
                    anim.start();
                } else { // 不支持动画，则直接设置不可见
                    reset.setVisibility(View.INVISIBLE);
                    reset.setBackgroundColor(R.color.bgColor);
                    reset.setTextColor(Color.GRAY);
                }
                for (int i = 0; i < mTextViews.size(); i ++){
                    if (((ColorDrawable)mTextViews.get(i).getBackground()).getColor() == getResources().getColor(R.color.fill)){
                        sign = i + 1 + 10;
                        mEditText.setText("");
                        text = "" + mBSRecord.getDataBySign(sign);
                        mEditText.setHint(text);
//                ToastUtil.showShort(getContext(), sign + "");
                    }
                }
            }
        });

        return view;
    }

    /**
     * 更新sign
     */
    private void updateSign() {
        mBSRecord.setDataBySign(sign, Double.parseDouble(text));
        for (int i = 0; i < mTextViews.size(); i ++){
            if (((ColorDrawable)mTextViews.get(i).getBackground()).getColor() == getResources().getColor(R.color.fill)){
                sign = i + 1 + 10;
                mEditText.setText("");
                text = "" + mBSRecord.getDataBySign(sign);
                mEditText.setHint(text);
//                ToastUtil.showShort(getContext(), sign + "");
            }
        }
    }

    /**
     * 暂停时马上保存数据到数据库
     */
    @Override
    public void onPause() {
        super.onPause();
        mBSRecord.setDataBySign(sign, Double.parseDouble(text));
        BSRecordHolder.get(getContext()).updateDate(mBSRecord);
    }

}
